const TANK_SIZE = 32;
class Tank {
  constructor(scene, x, y) {
    this.scene = scene;
    this.x = x;
    this.y = y;
    this.speed = 100;
    this.dir = 0; // 0: 上, 1: 下, 2: 左, 3: 右

    this.sprite = scene.physics.add.sprite(x, y, 'tankall')
      .setCrop(0, 0, TANK_SIZE, TANK_SIZE)
      .setOrigin(0);

  }

  update(cursors, dt) {
    if (cursors.left.isDown) {
      this.dir = 2;
      this.x -= this.speed * dt;
    } else if (cursors.right.isDown) {
      this.dir = 3;
      this.x += this.speed * dt;
    }

    if (cursors.up.isDown) {
      this.dir = 0;
      this.y -= this.speed * dt;
    } else if (cursors.down.isDown) {
      this.dir = 1;
      this.y += this.speed * dt;
    }

    // 根据方向设置剪裁区域
    const frameMap = {
      0: [0, 0],    // 上
      1: [32, 0],   // 下
      2: [64, 0],   // 左
      3: [96, 0]    // 右
    };
    const [cropX, cropY] = frameMap[this.dir];

    this.sprite.setCrop(cropX, cropY, TANK_SIZE, TANK_SIZE);
    this.sprite.x = this.x;
    this.sprite.y = this.y;
 
  }
}

//AI tank
class EnemyTank {
  constructor(scene, x, y) {
    this.scene = scene;
    this.x = x;
    this.y = y;
    this.speed = 50;
    this.dir = Phaser.Math.Between(0, 3); // 初始随机方向
    this.sprite = scene.add.sprite(x, y, 'tankall')
      .setCrop(0, 0, TANK_SIZE, TANK_SIZE)
      .setOrigin(0);

    this.timer = 0;
    this.fireCooldown = 2000; // 每 2 秒发射一次
  }

  update(dt, bulletManager) {
    // 移动
    const moveDist = this.speed * dt;
    switch (this.dir) {
      case 0: this.y -= moveDist; break; // 上
      case 1: this.y += moveDist; break; // 下
      case 2: this.x -= moveDist; break; // 左
      case 3: this.x += moveDist; break; // 右
    }

    // 更换方向（随机间隔改变方向）
    if (Math.random() < 0.01) {
      this.dir = Phaser.Math.Between(0, 3);
    }

    // 更新位置和图像
    const frameMap = {
      0: [0, 0], 1: [32, 0],
      2: [64, 0], 3: [96, 0]
    };
    const [cropX, cropY] = frameMap[this.dir];
    this.sprite.setCrop(cropX, cropY, TANK_SIZE, TANK_SIZE);
    this.sprite.x = this.x;
    this.sprite.y = this.y;

    // 发射子弹（定时）
    this.timer += dt * 1000;
    if (this.timer > this.fireCooldown) {
      const offset = (TANK_SIZE - 16) / 2;
      bulletManager.shoot(this.x + offset, this.y + offset, this.dir, 'fire','enemy');
      this.timer = 0;
    }


    

  }
}
